package org.wukongcrm.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.wukongcrm.domain.entity.AdminUser;
import org.wukongcrm.domain.entity.Menu;
import org.wukongcrm.domain.model.LoginUser;
import org.wukongcrm.domain.model.R;
import org.wukongcrm.mapper.MenuMapper;
import org.wukongcrm.utils.JwtUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * token拦截器
 *
 * @author ZhongWang
 * @since 2024 12 24:18:05
 */
@Slf4j
@Component
@AllArgsConstructor
public class TokenFilter extends OncePerRequestFilter {

    private static final List<String> WHITE_LIST = Arrays.asList("/login");
    private static final String AUTH_HEADER = "token";
    private static final String REDIS_KEY_PREFIX = "permission:";
    private static final boolean IS_DEBUG = true;

    private final StringRedisTemplate stringRedisTemplate;

    private final ObjectMapper objectMapper;

    private final MenuMapper permissionsMapper;


    @Override
    protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        log.debug("Request URI: {}", uri);

        if(IS_DEBUG){
            List<Menu> permissions = permissionsMapper.selectList(null);
            LoginUser loginUser = new LoginUser();
            AdminUser adminUser = new AdminUser(1,"admin","1234",null,null,null,null,null,null,null,null,null,null,null,null);
            loginUser.setUsers(adminUser);
            loginUser.setPermissions(permissions);
            setAuthentication(loginUser);
            request.setAttribute("userNo", loginUser.getUsers().getUserNo());
            request.setAttribute("username", loginUser.getUsers().getUsername());
            request.setAttribute("userId", loginUser.getUsers().getUserNo());
            filterChain.doFilter(request, response);
            return;
        }

        if (WHITE_LIST.contains(uri)) {
            filterChain.doFilter(request, response);
            return;
        }


        String token = request.getHeader(AUTH_HEADER);
        if (token != null) {
            if (isTokenExpired(token)) {
                postLoginAuthenticationMsg(response, "登录已过期，请重新登录");
                return;
            }

            String username = JwtUtils.getUsername(token);
            String cacheUser = getUserFromRedis(username);
            if (cacheUser == null) {
                postLoginAuthenticationMsg(response, "你已经被强制下线，请重新登录");
                return;
            }

            LoginUser loginUser = objectMapper.readValue(cacheUser, LoginUser.class);
            setAuthentication(loginUser);
            request.setAttribute("userId", loginUser.getUsers().getUserNo());
            filterChain.doFilter(request, response);
        } else {
            postLoginAuthenticationMsg(response, "你还没有登录，请先登录");
        }
    }

    private boolean isTokenExpired (String token) {
        return JwtUtils.isExpired(token);
    }

    private String getUserFromRedis (String username) {
        return stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX + username);
    }

    private void setAuthentication (LoginUser loginUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

    private void postLoginAuthenticationMsg (HttpServletResponse response, String msg) throws IOException {
        R<Object> r = R.error(401, msg, null);
        String msgJson = objectMapper.writeValueAsString(r);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(msgJson);
    }
}
